package zdream.control.foe.mm2pipi;

import java.util.ArrayList;
import java.util.List;

import zdream.control.region.ItemSpec;
import zdream.control.world.LevelWorld;
import zdream.control.world.MFoe;
import zdream.control.world.MHookType;
import zdream.utils.math.Rectangle;

/**
 * 这个生怪场可能有很多 box. 但是由 tmx 生成的只有一个 box
 *
 * @author Zdream
 * @since 0.0.1
 * @date 2020-06-11 (created)
 * @date 2022-06-11 (last modified)
 */
public class MM2PipiSpawnField extends MFoe {
	public static final String NAME = "MM2PipiSpawnField";

	public MM2PipiSpawnField(LevelWorld world) {
		super(world);
		this.type = TYPE_FIELD;
		this.side = SIDE_ENEMY;
	}

	@Override
	public String foeName() {
		return NAME;
	}

	@Override
	protected void prepare(ItemSpec... parameters) {
		super.prepare(parameters);
		for (ItemSpec param : parameters) {
			if (param == null || param.field == null) {
				continue;
			}

			if (param.field.spawnXSet) {
				spawnX = param.field.spawnX;
			}
			if (param.field.spawnYSet) {
				spawnY = param.field.spawnY;
			}

			this.setBox(0, 0, param.field.width, param.field.height);
			side = param.field.side;
		}
	}

	@Override
	public void init() {
		initTrigger();

		onHook(MHookType.TICK)
				.handle(this::checkSpawn)
				.buildAndSave();
	}

	/* **********
	 *   触发   *
	 ********** */
	/*
	 * 生成策略
	 */
	int firstDuration = 1000;
	int spawnDuration = 6000;

	/**
	 * 当前步是否触发
	 */
	public boolean active;

	/*
	 * 状态数据
	 */
	/**
	 * 到下一只怪生成的剩余时间, 毫秒
	 */
	public long spawnRemain;
	/**
	 * 怪生成的位置. x 或 y = null 时为自适应
	 * 自适应时, 怪从屏幕边缘出来, 屏幕上方, 按照当前照相机范围指定.
	 */
	public Float spawnX, spawnY;

	private void initTrigger() {
		spawnRemain = firstDuration;
	}

	public void checkSpawn() {
		// 检查是否触发
		checkActive();

		if (active) {
			spawnRemain -= world.ticker.lDuration;
		}
		if (spawnRemain <= 0) {
			spawn();
			spawnRemain = spawnDuration;
		}
	}

	private void spawn() {
		MM2Pipi pipi = new MM2Pipi(world);

		Rectangle viewBound = world.camera.view;
		float spx = (spawnX == null) ? viewBound.x + viewBound.width + 1 : spawnX,
			spy = (spawnY == null) ? viewBound.y + viewBound.height - 3 : spawnY;

		pipi.setVX(-7.5f);
		world.createFoe(pipi, spx, spy, false);
	}

	private static final List<MFoe> tmpArray = new ArrayList<>();
	private void checkActive() {
		active = false;
		// 阵营判断部分
		tmpArray.clear();
		world.findOverlapFoeAndPutInList(tmpArray, this.pos);
		if (tmpArray.isEmpty()) {
			return;
		}

		for (MFoe target : tmpArray) {
			if (side == target.side) {
				continue;
			}
			
			switch (target.type) {
			case TYPE_LEADER: case TYPE_FOE: case TYPE_ELITE:
				active = true;
				return;
			}
		}
	}
}
